<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <div class="import-export-dialog">
      <!-- 操作类型选择 -->
      <el-tabs v-model="activeOperation" class="operation-tabs">
        <el-tab-pane :label="$t('ImportExport.Import')" name="import">
          <div class="import-section">
            <!-- 模板下载 -->
            <div class="template-section">
              <h4>{{ $t('ImportExport.DownloadTemplate') }}</h4>
              <el-alert
                :title="$t('ImportExport.TemplateDescription')"
                type="info"
                :closable="false"
                show-icon
              />
              <div class="template-actions">
                <el-button type="primary" plain @click="downloadTemplate">
                  <el-icon><Download /></el-icon>
                  {{ $t('ImportExport.DownloadExcelTemplate') }}
                </el-button>
                <el-button type="success" plain @click="downloadTemplate('csv')">
                  <el-icon><Download /></el-icon>
                  {{ $t('ImportExport.DownloadCsvTemplate') }}
                </el-button>
              </div>
            </div>

            <!-- 文件上传 -->
            <div class="upload-section">
              <h4>{{ $t('ImportExport.UploadFile') }}</h4>
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-progress="handleUploadProgress"
                :file-list="fileList"
                :limit="1"
                :accept="acceptedFormats"
                :auto-upload="false"
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                  {{ $t('ImportExport.DragOrClick') }}
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    {{ $t('ImportExport.SupportedFormats') }}: {{ acceptedFormats }}
                  </div>
                </template>
              </el-upload>

              <!-- 上传进度 -->
              <div v-if="uploading" class="upload-progress">
                <el-progress :percentage="uploadProgress" :status="uploadStatus" />
                <div class="progress-info">
                  <span>{{ $t('ImportExport.Uploading') }}...</span>
                  <span v-if="uploadProgress > 0">{{ uploadProgress }}%</span>
                </div>
              </div>
            </div>

            <!-- 导入选项 -->
            <div class="import-options">
              <h4>{{ $t('ImportExport.ImportOptions') }}</h4>
              <el-form :model="importOptions" label-width="120px">
                <el-form-item :label="$t('ImportExport.ImportMode')">
                  <el-radio-group v-model="importOptions.mode">
                    <el-radio value="create">{{ $t('ImportExport.CreateOnly') }}</el-radio>
                    <el-radio value="update">{{ $t('ImportExport.UpdateOnly') }}</el-radio>
                    <el-radio value="upsert">{{ $t('ImportExport.CreateAndUpdate') }}</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item :label="$t('ImportExport.DuplicateHandling')">
                  <el-radio-group v-model="importOptions.duplicateHandling">
                    <el-radio value="skip">{{ $t('ImportExport.SkipDuplicates') }}</el-radio>
                    <el-radio value="overwrite">{{ $t('ImportExport.OverwriteDuplicates') }}</el-radio>
                    <el-radio value="fail">{{ $t('ImportExport.FailOnDuplicates') }}</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item :label="$t('ImportExport.ErrorHandling')">
                  <el-checkbox-group v-model="importOptions.errorHandling">
                    <el-checkbox value="continue">{{ $t('ImportExport.ContinueOnError') }}</el-checkbox>
                    <el-checkbox value="log">{{ $t('ImportExport.LogErrorDetails') }}</el-checkbox>
                    <el-checkbox value="rollback">{{ $t('ImportExport.RollbackOnError') }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item :label="$t('ImportExport.FieldMapping')">
                  <el-button type="text" @click="showFieldMapping = !showFieldMapping">
                    {{ $t('ImportExport.ConfigureMapping') }}
                  </el-button>
                </el-form-item>
              </el-form>

              <!-- 字段映射配置 -->
              <div v-if="showFieldMapping" class="field-mapping">
                <el-table :data="fieldMappings" size="small">
                  <el-table-column :label="$t('ImportExport.SourceField')" prop="sourceField" />
                  <el-table-column :label="$t('ImportExport.TargetField')">
                    <template #default="{ row }">
                      <el-select v-model="row.targetField" size="small">
                        <el-option
                          v-for="field in availableFields"
                          :key="field.name"
                          :label="field.displayName"
                          :value="field.name"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('ImportExport.Required')" width="80">
                    <template #default="{ row }">
                      <el-tag :type="row.required ? 'danger' : 'info'" size="small">
                        {{ row.required ? $t('Common.Yes') : $t('Common.No') }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 预览数据 -->
            <div v-if="previewData.length > 0" class="preview-section">
              <h4>{{ $t('ImportExport.DataPreview') }}</h4>
              <el-table :data="previewData" size="small" max-height="200">
                <el-table-column
                  v-for="column in previewColumns"
                  :key="column.prop"
                  :prop="column.prop"
                  :label="column.label"
                  show-overflow-tooltip
                />
                <el-table-column :label="$t('ImportExport.Status')" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)" size="small">
                      {{ getStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('ImportExport.Errors')" width="200">
                  <template #default="{ row }">
                    <div v-if="row.errors" class="error-list">
                      <div v-for="error in row.errors" :key="error" class="error-item">
                        {{ error }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane :label="$t('ImportExport.Export')" name="export">
          <div class="export-section">
            <!-- 导出选项 -->
            <div class="export-options">
              <h4>{{ $t('ImportExport.ExportOptions') }}</h4>
              <el-form :model="exportOptions" label-width="120px">
                <el-form-item :label="$t('ImportExport.ExportFormat')">
                  <el-radio-group v-model="exportOptions.format">
                    <el-radio value="excel">Excel (.xlsx)</el-radio>
                    <el-radio value="csv">CSV (.csv)</el-radio>
                    <el-radio value="json">JSON (.json)</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item :label="$t('ImportExport.DataRange')">
                  <el-radio-group v-model="exportOptions.range">
                    <el-radio value="all">{{ $t('ImportExport.AllData') }}</el-radio>
                    <el-radio value="filtered">{{ $t('ImportExport.FilteredData') }}</el-radio>
                    <el-radio value="selected">{{ $t('ImportExport.SelectedData') }}</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item :label="$t('ImportExport.FieldSelection')">
                  <el-button type="text" @click="showFieldSelection = !showFieldSelection">
                    {{ $t('ImportExport.SelectFields') }}
                  </el-button>
                </el-form-item>

                <el-form-item :label="$t('ImportExport.IncludeOptions')">
                  <el-checkbox-group v-model="exportOptions.includes">
                    <el-checkbox value="headers">{{ $t('ImportExport.IncludeHeaders') }}</el-checkbox>
                    <el-checkbox value="metadata">{{ $t('ImportExport.IncludeMetadata') }}</el-checkbox>
                    <el-checkbox value="timestamps">{{ $t('ImportExport.IncludeTimestamps') }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>

              <!-- 字段选择 -->
              <div v-if="showFieldSelection" class="field-selection">
                <el-transfer
                  v-model="exportOptions.selectedFields"
                  :data="availableFields"
                  :titles="[$t('ImportExport.AvailableFields'), $t('ImportExport.SelectedFields')]"
                  :props="{ key: 'name', label: 'displayName' }"
                />
              </div>
            </div>

            <!-- 导出预览 -->
            <div class="export-preview">
              <h4>{{ $t('ImportExport.ExportPreview') }}</h4>
              <div class="preview-stats">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-statistic
                      :title="$t('ImportExport.TotalRecords')"
                      :value="exportStats.totalRecords"
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-statistic
                      :title="$t('ImportExport.SelectedFields')"
                      :value="exportStats.selectedFields"
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-statistic
                      :title="$t('ImportExport.EstimatedSize')"
                      :value="exportStats.estimatedSize"
                      suffix="KB"
                    />
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('Common.Cancel') }}</el-button>
        <el-button
          v-if="activeOperation === 'import'"
          type="primary"
          :loading="loading"
          :disabled="!canImport"
          @click="handleImport"
        >
          {{ $t('ImportExport.StartImport') }}
        </el-button>
        <el-button
          v-else
          type="primary"
          :loading="loading"
          :disabled="!canExport"
          @click="handleExport"
        >
          {{ $t('ImportExport.StartExport') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, UploadFilled } from '@element-plus/icons-vue'
import { authService } from '@/services/AuthService'

interface Props {
  modelValue: boolean
  entityType: 'user' | 'tenant' | 'role'
  selectedItems?: any[]
  filters?: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', result: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const uploadRef = ref()
const activeOperation = ref('import')
const loading = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref<'success' | 'exception' | ''>('')
const fileList = ref([])
const showFieldMapping = ref(false)
const showFieldSelection = ref(false)
const previewData = ref([])
const previewColumns = ref([])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
  const entityMap = {
    user: $t('ImportExport.UserImportExport'),
    tenant: $t('ImportExport.TenantImportExport'),
    role: $t('ImportExport.RoleImportExport')
  }
  return entityMap[props.entityType] || $t('ImportExport.ImportExport')
})

const uploadUrl = computed(() => `/api/${props.entityType}/import`)
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${authService.getToken()}`
}))

const acceptedFormats = computed(() => '.xlsx,.xls,.csv,.json')

// 可用字段
const availableFields = computed(() => {
  if (props.entityType === 'user') {
    return [
      { name: 'userName', displayName: $t('Identity.UserName') },
      { name: 'email', displayName: $t('Identity.Email') },
      { name: 'name', displayName: $t('Identity.Name') },
      { name: 'surname', displayName: $t('Identity.Surname') },
      { name: 'phoneNumber', displayName: $t('Identity.PhoneNumber') },
      { name: 'isActive', displayName: $t('Common.Active') },
      { name: 'roleNames', displayName: $t('Identity.Roles') }
    ]
  } else if (props.entityType === 'tenant') {
    return [
      { name: 'name', displayName: $t('TenantManagement.TenantName') },
      { name: 'code', displayName: $t('TenantManagement.TenantCode') },
      { name: 'description', displayName: $t('TenantManagement.Description') },
      { name: 'isActive', displayName: $t('Common.Active') },
      { name: 'creationTime', displayName: $t('Common.CreationTime') }
    ]
  } else if (props.entityType === 'role') {
    return [
      { name: 'name', displayName: $t('Identity.RoleName') },
      { name: 'displayName', displayName: $t('Identity.DisplayName') },
      { name: 'description', displayName: $t('Identity.Description') },
      { name: 'isActive', displayName: $t('Common.Active') },
      { name: 'isDefault', displayName: $t('Identity.IsDefault') }
    ]
  }
  return []
})

// 字段映射
const fieldMappings = computed(() => {
  return availableFields.value.map(field => ({
    sourceField: field.displayName,
    targetField: field.name,
    required: ['userName', 'email', 'name'].includes(field.name)
  }))
})

// 导入选项
const importOptions = reactive({
  mode: 'upsert',
  duplicateHandling: 'skip',
  errorHandling: ['continue', 'log'],
  fieldMapping: {}
})

// 导出选项
const exportOptions = reactive({
  format: 'excel',
  range: 'all',
  selectedFields: availableFields.value.map(f => f.name),
  includes: ['headers', 'metadata', 'timestamps']
})

// 导出统计
const exportStats = computed(() => {
  const recordCount = props.selectedItems?.length || 1000
  const fieldCount = exportOptions.selectedFields.length
  const estimatedSize = Math.round((recordCount * fieldCount * 50) / 1024) // KB

  return {
    totalRecords: recordCount,
    selectedFields: fieldCount,
    estimatedSize
  }
})

// 是否可以导入
const canImport = computed(() => {
  return fileList.value.length > 0 && !uploading.value
})

// 是否可以导出
const canExport = computed(() => {
  return exportOptions.selectedFields.length > 0
})

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    valid: 'success',
    invalid: 'error',
    warning: 'warning',
    duplicate: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    valid: $t('ImportExport.Valid'),
    invalid: $t('ImportExport.Invalid'),
    warning: $t('ImportExport.Warning'),
    duplicate: $t('ImportExport.Duplicate')
  }
  return statusMap[status] || status
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isValidFormat = acceptedFormats.value
    .split(',')
    .some(format => file.name.toLowerCase().endsWith(format.trim()))

  if (!isValidFormat) {
    ElMessage.error($t('ImportExport.InvalidFileFormat'))
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error($t('ImportExport.FileSizeLimit'))
    return false
  }

  return true
}

// 上传进度处理
const handleUploadProgress = (event: any) => {
  uploading.value = true
  uploadProgress.value = Math.round(event.percent)
  uploadStatus.value = ''
}

// 上传成功处理
const handleUploadSuccess = (response: any) => {
  uploading.value = false
  uploadProgress.value = 100
  uploadStatus.value = 'success'

  if (response.success) {
    previewData.value = response.data.preview || []
    previewColumns.value = response.data.columns || []
    ElMessage.success($t('ImportExport.FileUploadSuccess'))
  } else {
    ElMessage.error(response.message || $t('ImportExport.FileUploadFailed'))
  }
}

// 上传错误处理
const handleUploadError = (error: any) => {
  uploading.value = false
  uploadStatus.value = 'exception'
  ElMessage.error($t('ImportExport.FileUploadFailed'))
  console.error('Upload error:', error)
}

// 下载模板
const downloadTemplate = async (format: string = 'excel') => {
  try {
    const url = `/api/${props.entityType}/template?format=${format}`
    const response = await fetch(url, {
      headers: {
        Authorization: `Bearer ${authService.getToken()}`
      }
    })

    if (!response.ok) {
      throw new Error('下载模板失败')
    }

    const blob = await response.blob()
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = `${props.entityType}-template.${format}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(downloadUrl)

    ElMessage.success($t('ImportExport.TemplateDownloadSuccess'))
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error($t('ImportExport.TemplateDownloadFailed'))
  }
}

// 处理导入
const handleImport = async () => {
  if (!uploadRef.value) return

  try {
    loading.value = true

    // 构建导入参数
    const importParams = {
      ...importOptions,
      fieldMapping: fieldMappings.value.reduce((acc, mapping) => {
        if (mapping.targetField) {
          acc[mapping.sourceField] = mapping.targetField
        }
        return acc
      }, {} as Record<string, string>)
    }

    // 开始上传
    uploadRef.value.submit()

    // 等待上传完成
    const checkUploadComplete = () => {
      return new Promise((resolve, reject) => {
        const interval = setInterval(() => {
          if (!uploading.value) {
            clearInterval(interval)
            if (uploadStatus.value === 'success') {
              resolve(previewData.value)
            } else {
              reject(new Error('Upload failed'))
            }
          }
        }, 500)
      })
    }

    await checkUploadComplete()

    // 显示导入结果
    const successCount = previewData.value.filter((item: any) => item.status === 'valid').length
    const errorCount = previewData.value.filter((item: any) => item.status === 'invalid').length

    let resultMessage = $t('ImportExport.ImportCompleted')
    resultMessage += `\n${$t('ImportExport.SuccessCount')}: ${successCount}`
    resultMessage += `\n${$t('ImportExport.ErrorCount')}: ${errorCount}`

    await ElMessageBox.alert(resultMessage, $t('ImportExport.ImportResult'), {
      confirmButtonText: $t('Common.OK'),
      type: errorCount > 0 ? 'warning' : 'success'
    })

    emit('success', {
      type: 'import',
      successCount,
      errorCount,
      data: previewData.value
    })

    handleClose()
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error($t('ImportExport.ImportFailed'))
  } finally {
    loading.value = false
  }
}

// 处理导出
const handleExport = async () => {
  try {
    loading.value = true

    // 构建导出参数
    const exportParams = {
      format: exportOptions.format,
      fields: exportOptions.selectedFields,
      filters: props.filters,
      range: exportOptions.range,
      includes: exportOptions.includes,
      itemIds: props.selectedItems?.map(item => item.id) || []
    }

    const response = await fetch(`/api/${props.entityType}/export`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${authService.getToken()}`
      },
      body: JSON.stringify(exportParams)
    })

    if (!response.ok) {
      throw new Error('导出失败')
    }

    const blob = await response.blob()
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl

    const timestamp = new Date().toISOString().slice(0, 10)
    const extension = exportOptions.format === 'excel' ? 'xlsx' : exportOptions.format
    link.download = `${props.entityType}-export-${timestamp}.${extension}`

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(downloadUrl)

    ElMessage.success($t('ImportExport.ExportSuccess'))

    emit('success', {
      type: 'export',
      format: exportOptions.format,
      recordCount: exportStats.value.totalRecords
    })

    handleClose()
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error($t('ImportExport.ExportFailed'))
  } finally {
    loading.value = false
  }
}

// 处理关闭
const handleClose = () => {
  if (loading.value || uploading.value) return

  dialogVisible.value = false
  setTimeout(() => {
    activeOperation.value = 'import'
    fileList.value = []
    previewData.value = []
    previewColumns.value = []
    showFieldMapping.value = false
    showFieldSelection.value = false
    uploadProgress.value = 0
    uploadStatus.value = ''

    // 重置选项
    Object.assign(importOptions, {
      mode: 'upsert',
      duplicateHandling: 'skip',
      errorHandling: ['continue', 'log'],
      fieldMapping: {}
    })

    Object.assign(exportOptions, {
      format: 'excel',
      range: 'all',
      selectedFields: availableFields.value.map(f => f.name),
      includes: ['headers', 'metadata', 'timestamps']
    })
  }, 300)
}

// 监听实体类型变化
watch(() => props.entityType, () => {
  exportOptions.selectedFields = availableFields.value.map(f => f.name)
})
</script>

<style scoped>
.import-export-dialog {
  min-height: 500px;
}

.operation-tabs {
  margin: -20px;
}

.template-section,
.upload-section,
.import-options,
.export-options,
.preview-section,
.export-preview {
  margin-bottom: 30px;
}

.template-section h4,
.upload-section h4,
.import-options h4,
.export-options h4,
.preview-section h4,
.export-preview h4 {
  margin-bottom: 15px;
  color: #303133;
  font-weight: 500;
}

.template-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.upload-demo {
  width: 100%;
}

.upload-progress {
  margin-top: 15px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.field-mapping,
.field-selection {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.error-list {
  font-size: 12px;
}

.error-item {
  color: #f56c6c;
  margin-bottom: 2px;
}

.preview-stats {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-transfer) {
  text-align: left;
}

:deep(.el-transfer-panel) {
  width: 45%;
}

:deep(.el-statistic__head) {
  font-size: 12px;
  color: #909399;
}

:deep(.el-statistic__content) {
  font-size: 20px;
  font-weight: 600;
}
</style>